package cn.pzhu.services.admin;

import cn.pzhu.constant.ConstantLogin;
import cn.pzhu.model.Privilege;
import cn.pzhu.model.Role;
import cn.pzhu.model.User;
import cn.pzhu.services.BaseServices;
import cn.pzhu.util.EncryptUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by dongp on 2016/4/22.
 */
public class IndexServices extends BaseServices{

    /**
     *用户登录后验证
     * @param request
     * @param account
     * @param password
     * @return
     */
    public int validLogin(HttpServletRequest request, String account, String password) {
        List<User> users = User.dao.find("select * from user where account = ?", account);
        if(users == null || users.size() != 1) {
            request.setAttribute("msg","用户名或密码不正确");
            return ConstantLogin.login_info_0;// 用户不存在
        }
        User user = users.get(0);

        // 如果密码错误，则错误次数加1并保存
        int errorCount = user.getInt(User.column_errorcount).intValue();
        int maxCount = user.getInt(User.column_maxcount).intValue();
        boolean checkSign = EncryptUtil.checkSign(password, user.getStr(User.column_password), "MD5");
        if(!checkSign) {
            errorCount++;
            user.findById(user.getInt("userID")).set(User.column_errorcount, errorCount).update();
            request.setAttribute("errorCount", maxCount - errorCount);
            request.setAttribute("msg","用户名或密码不正确");
            return ConstantLogin.login_info_2;// 密码错误
        }

        // 密码错误次数超限
        if(errorCount > maxCount) {
            request.setAttribute("msg","用户已被锁定，请联系管理员");
            return ConstantLogin.login_info_3;
        }

        // 判断是否管理员
        int roleVal = user.getInt(User.column_roleVal);
        if(roleVal != 1) {
            request.setAttribute("msg","你的权限不足，请联系管理员");
           return ConstantLogin.login_info_4;
        }
        List<Privilege> privileges = Privilege.dao.find("select * from privilege where masterVal = ?",roleVal);

        HttpSession session = request.getSession();
        session.setAttribute("user",user);
        session.setAttribute("privileges",privileges);
        request.setAttribute("isLogin", true);
        return ConstantLogin.login_info_1;// 用户验证成功
    }

}
